# -*- coding: utf-8 -*-
# @Author: XiaoRui
# @FileName: pipe.py
# @Time: 2021/4/28 20:12
# @Software: PyCharm

import win32file
import win32pipe
import struct
import threading


def recv_pipe(PIPE_NAME, PIPE_BUFFER_SIZE):
    while True:
        named_pipe = win32pipe.CreateNamedPipe(PIPE_NAME,
                                               win32pipe.PIPE_ACCESS_DUPLEX,
                                               win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_WAIT | win32pipe.PIPE_READMODE_MESSAGE,
                                               win32pipe.PIPE_UNLIMITED_INSTANCES,
                                               PIPE_BUFFER_SIZE,
                                               PIPE_BUFFER_SIZE, 500, None)
        try:
            while True:
                try:
                    win32pipe.ConnectNamedPipe(named_pipe, None)
                    data = win32file.ReadFile(named_pipe, PIPE_BUFFER_SIZE, None)
                    if data is None:
                        continue
                    # print("Received msg:", data)
                    recv_msg = struct.unpack('<2s', data[1])
                    recv_msg = recv_msg[0].decode("utf-8")
                    print("Parsed message:", recv_msg)
                except BaseException as e:
                    print("Exception1:", e)
                    break
        finally:
            try:
                win32pipe.DisconnectNamedPipe(named_pipe)
            except BaseException as e:
                print("Exception2:", e)
                break


if __name__ == "__main__":
    pipe_name = r"\\.\pipe\test_pipe"
    pipe_buffer_size = 65535
    receive_thread = threading.Thread(target=recv_pipe, args=(pipe_name, pipe_buffer_size))
    receive_thread.start()
